import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
let listData = window.sessionStorage.getItem('listData')
let store =  new Vuex.Store({
  state: {
    listData: listData?JSON.parse(listData):{},
    token: window.sessionStorage.getItem('token') || '',
  },
  getters: {
    getDetail(state) {
      return (id,tag) => {
        let detail = state.listData[tag].filter((v,i) => {
          return v.id*1 === id*1
        })[0]
        return detail;
      }
    }
  },
  mutations: {
    setListData(state, data) {
      // 为什么用对象， 为了避免重复插入数据， 方便判断
      if(!state.listData[data.tag]) {
        Vue.set(state.listData, data.tag, data.data)
      }
      
    },
    setMessageList(state,data) {
      // tag, id,
      // let list = state.listData[data.tag*1];
      // let index = list.findIndex((v,i) => {
      //   return v.id ===data.id
      // })
      // if(index !== -1) {
        data.detailData.detail.list.push(data.data);
      // }
    },
    delMessageList(stata,data) {
      data.detailData.detail.list.forEach((v,i) => {
        if(v.id === data.msgId) {
          data.detailData.detail.list.splice(i,1)
        }
      })
    },
    like(stata,data) {
      data.detailData.detail.list.forEach((v,i) => {
        if(v.id === data.msgId) {
          v.likeCount++;
        }
      })
    },
    setToken(state,token) {
      state.token = token;
    }
  },
  actions: {
  },
  modules: {
  }
})

store.subscribe((mutations,state) => {
    if(state.listData) {
      window.sessionStorage.setItem('listData', JSON.stringify(state.listData))
    }
    if(state.token) {
      window.sessionStorage.setItem('token', state.token)
    }
})
export default store;
